package com.haiheng.module_main.service

import android.app.Service
import android.content.Intent
import android.os.IBinder
import androidx.lifecycle.ViewModelProvider
import com.haiheng.common.constant.AppConstant
import com.haiheng.library.log.LogUtils
import com.haiheng.library.log.LogWriter
import com.haiheng.module_main.mode.MainViewModel
import java.util.*

/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2023/4/19 0019
 * @Version: 1.0
 */
class ReportService : Service() {
    private var timer: Timer? = null
    private val viewModel: MainViewModel by lazy {
        ViewModelProvider.AndroidViewModelFactory(application).create(MainViewModel::class.java)
    }

//    var reportTiem:Long =  1000 * 60 * 60 //每隔一小时执行一次上报操作
    var reportTiem:Long =  1000 * AppConstant.getReportInterval().toLong() //每隔一小时执行一次上报操作
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        LogWriter.d("ReportService onStartCommand")
        // 创建定时器
        timer = Timer()
        // 启动定时任务
        timer?.schedule(object : TimerTask() {
            override fun run() {
                // 执行上报操作
                LogUtils.d("ReportService ${this.hashCode()}")
                reportDataToServer()
            }
        }, 0, reportTiem) //

        // 返回 START_STICKY，表示 Service 在被杀掉后可以自动重启
        return START_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
        LogWriter.e("ReportService onDestroy")
        // 停止定时器
        stopService(Intent(this, ReportService::class.java))
        timer?.cancel()
        timer = null
    }

    override fun onBind(intent: Intent?): IBinder? {
        LogWriter.d("ReportService onBind")
        return null
    }

    private fun reportDataToServer() {
        // 执行上报操作

        viewModel.reportStatus()
    }
}
